//客户池表单表格
var $customerPoolTable = $('#customerPoolTableList');
var abs = new verjs_select();
//防止表头与表格不对齐
$(window).resize(function () {
    $customerPoolTable.bootstrapTable('resetView');
});

$(function () {
    // 创建时间
    $('#createTm').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    //初始化客户池表单
    customerPoolTableListInit();
    getProvince();
    getCity('110000');
    $('#searchBox').css('display', 'none');
    $('#companyLabel').css('display', 'none');
    $('#companyDiv').css('display', 'none');
    $('#timeLimitLabel').css('display', 'none');
    $('#timeLimitDiv').css('display', 'none');
    //loadCompanyListData();
    loadCompanySelect();

    // 高级筛选
    $('#filterContent').on('show.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-close"></i>关闭筛选');
    }).on('hide.bs.collapse', function () {
        $('.btn-senior').html('<i class="mdi mdi-sort-variant"></i>高级筛选');
    }).on('hidden.bs.collapse', function () {
        resetCustomerPoolQueryParams('#filterContent');
    });
});

// 渲染城市列表
function getProvince() {
    let provinceNames = [];
    $.each(cityJson[0], function (key, value) {
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    $('#province').selectpicker('refresh');
    //getCity('110000');
}

// 根据省获取市
function getCity(provinceId) {
    let key = '0,' + provinceId;
    var flag = cityJson.hasOwnProperty(key);
    if(flag){
        $('#city').html('');
        let cityNames = [];
        $.each(cityJson[key], function (key, value) {
            cityNames.push('<option value="' + key + '">' + value + '</option>')
        });
        $('#city').html(cityNames.join(''));
        $('#city').selectpicker('refresh');
    }
}

// '切换城市'
function changeCity() {
    getCity($('#province').val())
}

// 池子
function seleceChi(type) {
    if (type == 2 ) {
        $('#searchBox').css('display', 'inline-block');
        $('#companyLabel').css('display', 'none');
        $('#companyDiv').css('display', 'none');
        $('#timeLimitLabel').css('display', 'none');
        $('#timeLimitDiv').css('display', 'none');
        $('#companySelect').val('').selectpicker('refresh');
    } else {
        $('#searchBox').css('display', 'none');
        $('#companyLabel').css('display', 'block');
        $('#companyDiv').css('display', 'block');
        $('#timeLimitLabel').css('display', 'block');
        $('#timeLimitDiv').css('display', 'flex');
        $("#searchBox").html('');
        $("#searchBox").append('<div id="search" style="margin-left: 16px;width: 230px;"></div>')
        abs.render({
            elem: "#search",
            data: "",
            init_value: [1],
            body_height: 300,
            checkbox: true,
            name: "test"
        });
    }
}

/**
 * 加载公司列表
 */
function loadCompanyListData(customerPoolId) {
    $.ajax({
        url: "/customer/selectCustomerPoolCompany?customerPoolId=" + customerPoolId,
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    var selectDate = [];
                    var selectDataId = [];
                    for (var i = 0, len = data.data.length; i < len; i++) {
                        var company = data.data[i];
                        var selectCompany = {};
                        selectCompany.id = company.companyId;
                        selectCompany.name = company.companyName;
                        selectDate.push(selectCompany);
                        if (company.selected) {
                            selectDataId.push(company.companyId)
                        }
                    }
                    $("#searchBox").html('');
                    $("#searchBox").append('<div id="search" style="margin-left: 16px;width: 230px;"></div>')
                    abs.render({
                        elem: "#search",
                        data: selectDate,
                        init_value: selectDataId,
                        body_height: 300,
                        checkbox: true,
                        name: "test"
                    });
                    $('#searchoption-list').css('z-index',1000);
                } else {
                    $.alert("查询所有公司失败");
                }

            }
        },
        error: function () {
            $.alert('查询所有公司异常');
        }
    });
}

/**
 * 加载全国池关联公司下拉列表
 */
function loadCompanySelect() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">请选择所属公司</option>';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companySelect").html("");
            $('#companySelect').append(companyOptionHtml);
            $('#companySelect').selectpicker('refresh');
        }
    });
}

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    $('#createTm').val('');//清空创建时间搜索条件
    $customerPoolTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 客户池表单--分页列表页
 */
function customerPoolTableListInit() {
    //先销毁表格
    $customerPoolTable.bootstrapTable('destroy');
    $customerPoolTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/customer/customerPoolList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerPoolId',
        idField: 'customerPoolId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerPoolId', visible: false},
            /*{title: '全选', field: 'checked', align: 'center', checkbox: true, valign: 'middle',width: '6%'},*/
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title: '客户池名称',field: 'customerPoolName',sortable: true,align: 'left', valign: 'middle'},
            {title: '客户池类别', field: 'nature', sortable: true, align: 'left', valign: 'middle',formatter: natureFormat},
            {title: '创建人', field: 'createPeopleName', sortable: true, align: 'left', valign: 'middle'},
            {title: '创建时间', field: 'createTm', sortable: true, align: 'left', valign: 'middle'},
            {title: '标签', field: 'tag', sortable: true, align: 'left', valign: 'middle', formatter: tagFormat},
            {title: '类型', field: 'poolType', sortable: true, align: 'left', valign: 'middle',formatter: poolTypeFormat},
           /* {title: '使用比例', field: 'useProportion', align: 'center', valign: 'middle'},
            {title: '客户数量', field: 'customerCount', align: 'center', valign: 'middle'},
            {title: '客户池容量', field: 'capacity', align: 'center', valign: 'middle'},*/
            {title: '操作',field: 'operate',align: 'right',events: operateEvents,formatter: genderOpt},
            {title: '是否启用',field: 'poolState',align: 'center',formatter: poolStateFormat},
            {field: '是否是默认池子', field:"defaultMark", visible: false},
            {field: '城市ID', field: 'cityId', visible: false},
            {field: '行业', field: 'industry', visible: false},
            {field: '公司ID', field: 'companyId', visible: false}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table操作列下拉菜单效果
            tableNav();

            var isAdmin = $('#isAdmin').val();
            if (isAdmin != 'true') {
                $customerPoolTable.bootstrapTable('hideColumn', 'poolState');//是否启用
            }
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 拼接客户池表格查询条件参数
 */
function advancedQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //普通搜索条件
    params.customerPoolName = $.trim($('#customerPoolNameSearch').val());//客户池名称
    params.tag = $.trim($('#tag').val());//客户池标签
    params.createTm = $('#createTm').val();//创建时间
    return params;
}
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)

    //普通搜索条件
    params.customerPoolName = $.trim($('#customerPoolNameMin').val());//客户池名称
    return params;
}

/**
 * 客户池类型(优、良、一般)
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function poolTypeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>优</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>良</span>";
    }else if(3 == value){
        return "<span class='label label-warning-light'>一般</span>";
    }
}

/**
 * 客户池类别格式化
 * @param value
 * @param row
 * @param index
 * @returns {string}
 *
 */
function natureFormat(value, row, index){
    if (value == null || value == undefined) {
        return "-";
    } else if (1 == value) {
        return "<span class='label label-success-light'>全国公有池</span>";
    } else if (2 == value) {
        return "<span class='label label-info-light'>分公司公有池</span>";
    }
}

/**
 * 客户池停用/启用状态
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function poolStateFormat(value, row, index){
    if(row.defaultMark == '1'){//defaultMark:默认池
        return '';
    }
    var is_checked = '';
    if (value == null || value == undefined || value == 0) {
        return "-";
    }else if (value == 2) {
        is_checked = '';
    } else if (value == 1) {
        is_checked = 'checked="checked"';
    }
    var poolStateHtml = '<label class="lyear-switch switch-solid switch-success">' +
        '<input type="checkbox" id="poolState' + row.customerPoolId  + '" ' + is_checked + '>' +
        '<span  onClick="updatePoolState(\'' + row.customerPoolId + '\', \'' + value + '\')"></span>' +
        '</label>';
    return poolStateHtml;
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    if(row.defaultMark == '1' || (!row.isAdmin && row.nature == '1')){//defaultMark:默认池；isAdmin：是否超管；nature：客户池性质
        html += '<button class="btn btn-default" id="detail" style="margin-right: 25px;"><i class="mdi mdi-eye"></i>查看</button>';
    } else {
        html += '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
        html += '<div class="dropdown"><button class="btn btn-link" data-index="' + index + '"><i class="mdi mdi-dots-vertical"></i></button><ul class="dropdown-menu">';
        html += '<li><a href="#!" id="edit">修改</a></li>';
    }
    html += '</ul></div>'
    return html;
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    //查看点击事件
    'click #detail': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '客户池详情',
            url : "/front/customerManager/customerPoolDetail?customerPoolId=" + row.customerPoolId
                + "&poolState=" + row.poolState + "&nature=" + row.nature
        }, true);
    },
    //编辑点击事件
    'click #edit': function (e, value, row, index) {
        $("#editModel").find('input[type=text],select').each(function() {
            $(this).val('').selectpicker('refresh');
        });
        showEditCustomerPool(row);
        loadCompanyListData(row.customerPoolId);
        $('#editModel').modal('show');
    },
    //删除点击事件
    /*'click #delete':function (e, value, row, index) {
        deleteCustomerPool(row.customerPoolId);
    },*/
};

/**
 * 开启/停用客户池
 * @param poolId
 * @param poolState
 */
function updatePoolState(customerPoolId, poolState){
    var poolState = (poolState == 1) ? 2 : 1; // 发送参数值跟当前参数值相反
    var confirmMessage = '';
    if (poolState == 1) {
        confirmMessage = "确定启用吗？";
    } else {
        confirmMessage = "确定停用吗？";
    }

    $.alert({
        title: '提示',
        content: confirmMessage,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customer/updatePoolState",
                        data: {
                            customerPoolId: customerPoolId,
                            poolState: poolState
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $customerPoolTable.bootstrapTable('updateCellById', {id: customerPoolId, field: 'poolState', value: poolState});
                            } else {
                                $.alert(data.message);
                                $customerPoolTable.bootstrapTable('updateCellById', {id: customerPoolId, field: 'poolState', value: poolState}); // 因开关点击后样式是变的，失败也重置下
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                            $customerPoolTable.bootstrapTable('updateCellById', {id: customerPoolId, field: 'poolState', value: poolState}); // 因开关点击后样式是变的，失败也重置下
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                    if(poolState == 1){
                        $("#poolState" + customerPoolId).prop('checked',false);
                    }else {
                        $("#poolState" + customerPoolId).prop('checked',true);
                    }
                }
            }
        }
    });
}

/**
 * 搜索点击事件
 */
var getProvinceId = '';
var getIndustry = '';
var getHotTag = '';
function searchCustomerPoolList(type,value){
    console.log(value)
    $('.all').addClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");
    if (type === 1) {//普通条件查询
        $customerPoolTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetCustomerPoolQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#customerPoolNameMin').val('');
        $customerPoolTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    } else if (type == 3) {//按地区查询
        getProvinceId = value;
        $customerPoolTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: function(params){
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)
                params.provinceId = getProvinceId; //省份ID
                params.industry = getIndustry;//行业
                params.hotTag = getHotTag;//热门标签
                return params;
            }});
    } else if(type == 4) {//按行业查询
        getIndustry = value;
        $customerPoolTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: function(params){
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)
                params.provinceId = getProvinceId; //省份ID
                params.industry = getIndustry;//行业
                params.hotTag = getHotTag;//热门标签
                return params;
            }});
    } else if (type == 5) {//按标签查询
        getHotTag = value;
        $customerPoolTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: function(params){
                params.pageSize = params.limit;
                params.pageIndex = (params.offset / params.limit) + 1;
                params.sortName = params.sort; //排序列名
                params.sortOrder = params.order;//排序方式
                params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)
                params.provinceId = getProvinceId; //省份ID
                params.industry = getIndustry;//行业
                params.hotTag = getHotTag;//热门标签
                return params;
            }});
    }
    // 地区、行业、热门条件点击切换背景
    $('.selector-box').on('click', 'a', function () {
        $(this).parents('dl').find('a').removeClass('active');
        $(this).addClass('active');
    });
}

/**
 * 重置客户池清单查询条件
 */
function resetCustomerPoolQueryParams(_this){
    let searchForm = '';
    if($(_this).parents('#filterContent').context == document) {
        searchForm = $(_this);
    } else {
        searchForm = $(_this).parents('#filterContent');
    }
    searchForm.find('input[type="text"]').val('');
    /*searchForm.find('select').find('option:first').prop('selected', 'selected');
    // 刷新下拉菜单selectpicker控件
    searchForm.find('select').selectpicker('refresh');*/

    // 点击重置按钮时，刷线table内容
    if($(_this).parents('#filterContent').context !== document) {
        customerPoolTableListInit();
    }
}

//清空所有搜索条件
function clearAllData() {
    //全部 本年 本月 本周
    $('.all').addClass('active-second');
    $('.year').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $("#dateType").val("all");
    //客户池名称
    $('#customerPoolNameSearch').val('');
    $('#customerPoolNameMin').val('');
    //创建时间
    $('#createTm').val('');
    //客户标签
    $('#tag').val('');
    customerPoolTableListInit()
}

/**
 * 新增客户池
 */
function addCustomerPool(){
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '创建客户池',
        url : "/front/customerManager/addCustomerPool"
    }, true);
}

function tagFormat(value, row, index) {
    var valTip;
    if(value.length>9) {
        valTip = value.substring(0, 8)+"..."
    } else {
        valTip = value
    }
    return [
        '<span style="color: #4d5259" href="#" data-html="true" data-toggle="tooltip" title=' + value + '>' + valTip + '</span>',
    ].join('');
}

function showEditCustomerPool(row){
    getProvince();
    getCity('110000');
    let key = '0,' + row.provinceId;
    //客户池主键
    $("#customerPoolId").val(row.customerPoolId);
    //客户池名称
    $("#customerPoolName").val(row.customerPoolName);
    //来源
    $("#source").val(row.source);
    //所在地区
    var flag = cityJson.hasOwnProperty(key);
    if(flag) {
        $('#province').selectpicker('val', row.provinceId);
        getCity(row.provinceId);
        $('#city').selectpicker('val', row.cityId);
    }
    // 标签
    $("#tagBox").html('');
    $("#tagBox").append('<input type="text" name="staticPath" value="" id="staticPath2"/>');
    $("#staticPath2").val('');
    $("#staticPath2").val(row.tag.split(','));
    WS({
        el: "#staticPath2",
    });
    //所在行业
    $('#industry').selectpicker('val', row.industry);
    //客户池类型
    $('#poolType').selectpicker('val', row.poolType);
    //所属公司
    $('#companySelect').selectpicker('val', row.affiliatedCompanyId);
    //客户池容量
    $("#capacity").val(row.capacity);
    //客户池性质
    var nature = row.nature;
    seleceChi(nature);
    $(":radio[name='nature'][value='" + nature + "']").prop("checked", "checked");
    $.ajax({
        url: "/customer/selectCustomerPoolRule?customerPoolId=" + row.customerPoolId,
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    var jsonObject = data.data;
                    $("#maximumNumber").val(jsonObject.maximumNumber);
                    $("#timeInterval").val(jsonObject.timeInterval);
                    $("#anyTimeInterval").val(jsonObject.anyTimeInterval);
                    $("#timeLimit").val(jsonObject.timeLimit);
                    $("#returnInterval").val(jsonObject.returnInterval);
                }
            }
        }
    });
    //客户池详情
    $("#addDetail").text(row.poolDetail);
}


function editCustomerPool(){
    var customerPoolId = $.trim($("#customerPoolId").val());
    //客户池名称
    var customerPoolName = $.trim($("#customerPoolName").val());

    //来源
    var source = $.trim($("#source").val());

    //省份id
    var provinceId = $('#province').val();

    //省份名称
    var provinceName = $("#province").find("option:selected").text();

    //城市id
    var cityId = $('#city').val();

    //城市名称
    var cityName = $("#city").find("option:selected").text();

    //行业
    var industry =  $("#industry").val();

    //客户池类型
    var poolType = $('#poolType').val();

    //客户池容量
    var capacity = $("#capacity").val();

    var tagStr = $('.fm-button').text().split(' ').join(',');
    var tagStrNew = tagStr.substring(0, tagStr.lastIndexOf(','))+ tagStr.substring(tagStr.lastIndexOf(',')+1);
    //客户池标签
    var tag = tagStrNew;
    //性质
    var nature = $("input[name='nature']:checked").val();

    //公司id
    var selectCompany = [];
    selectCompany = abs.get_value('search');
    var companyIdList = [];
    for(let i=0;i<selectCompany.length;i++) {
        companyIdList.push(selectCompany[i].id);
    }
    //无跟进退回时间间隔
    var returnInterval = $("#returnInterval").val();

    //最多领取数量
    var maximumNumber = $("#maximumNumber").val();

    //同一客户不能连续领取间隔
    var timeInterval = $("#timeInterval").val();

    //任意客户不能连续领取间隔
    var anyTimeInterval = $("#anyTimeInterval").val();

    //客户池详情
    var poolDetail = $.trim($("#addDetail").val());

    //全国公有池 所属公司
    var affiliatedCompanyId = $("#companySelect").val();

    //其它公司时间限制
    var timeLimit = $("#timeLimit").val();

    //客户池名称为空和长度验证
    if (!customerPoolName) {
        $.alert("客户池名称不能为空!");
        return;
    } else {
        if (customerPoolName.length > 50) {
            $.alert("客户池名称长度不能大于50个字符！");
            return;
        }
    }

    //所在行业
    if (!industry) {
        $.alert("所在行业不能为空!");
        return;
    }

    //标签为空判断
    if(!tag){
        $.alert("标签不能为空！");
        return;
    }

    //客户池容量判断
    if(!capacity){
        $.alert("客户池容量不能为空！");
        return;
    }

    //客户池性质
    if(!nature){
        $.alert("客户池性质必选！");
        return;
    }
    if (nature == 2) {
        if(companyIdList.length == 0){
            $.alert("分公司必选！");
            return;
        }
    }

    //最多领取数量
    if(!maximumNumber){
        $.alert("最多领取数量必填！");
        return;
    }

    //同一客户不能连续领取间隔
    if(!timeInterval){
        $.alert("同一客户不能连续领取间隔必填！");
        return;
    }

    //任意客户不能连续领取间隔
    if(!anyTimeInterval){
        $.alert("任意客户不能连续领取间隔必填！");
        return;
    }

    //无跟进时间间隔验证
    if(!returnInterval){
        $.alert("无跟进退回时间间隔必填！");
        return;
    }

    //客户池详情
    if (poolDetail.length > 65535) {
        $.alert("//客户池详情长度不能大于65535个字符！");
        return;
    }

    var jsonData = {
        "customerPoolId":customerPoolId,
        "customerPoolName":customerPoolName,
        "source":source,
        "provinceId":provinceId,
        "provinceName":provinceName,
        "cityId":cityId,
        "cityName":cityName,
        "industry":industry,
        "poolType":poolType,
        "capacity":capacity,
        "tag":tag,
        "nature":nature,
        "companyIdList":companyIdList,
        "returnInterval":returnInterval,
        "maximumNumber":maximumNumber,
        "timeInterval":timeInterval,
        "anyTimeInterval":anyTimeInterval,
        "poolDetail":poolDetail,
        "affiliatedCompanyId":affiliatedCompanyId,
        "timeLimit":timeLimit
    };
    $.ajax({
        url: '/customer/editCustomerPool',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                /*var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("客户公海","/front/customerManager/customerPoolForm");
                                delStorageAndRemove(navTab);*/
                                $('#editModel').modal('hide');
                                window.location.reload();
                            }
                        }
                    }
                });
            } else if(data.code == "CP0000"){
                $.alert("客户池名称重复！");
            } else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存异常");
        })
    });
}

function deleteCustomerPool(customerPoolId){
    $.ajax({
        url: "/customer/deleteCustomerPool?customerPoolId=" + customerPoolId,
        type: "POST",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        async: false,
        success: function (data) {
            if (data.code == '000000') {
                $.alert('删除成功!');
                $customerPoolTable.bootstrapTable('refresh');
            } else {
                $.alert('删除失败！');
                $customerPoolTable.bootstrapTable('refresh');
            }
        },
        error: function () {
            $.alert('删除异常,请稍后再试！');
        }
    })
}
